
#include <iostream>
#include <cassert>
#include <fstream>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;
// 剔除su2 网格中的重复列
inline string strip(string str)
{
    string::size_type posb, pose;
    posb = str.find_first_not_of(" \t");
    if (posb == string::npos)
        return "";
    pose = str.find_last_not_of(" \t");
    // return (pose != string::npos) ?
    // str.substr(posb, pose - posb + 1) : str.substr(posb);
    return str.substr(posb, pose - posb + 1);
}

int main()
{
    string filename{"mesh_ONERAM6_inv_ffd.su2"};
    ifstream input{filename};
    if (!input)
    {
        cerr << "cannot open " << filename << "\n";
        exit(EXIT_FAILURE);
    }
    ofstream output{"corrected_" + filename};

    string line, front, back;
    string::size_type pos;
    stringstream sstr;
    while (getline(input, line))
    {
        pos = line.find_first_of('=');
        if (pos == string::npos)
        {
            output << line << "\n";
            continue;
        }
        front = strip(line.substr(0, pos));
        if (front == "NPOIN")
        {
            back = strip(line.substr(pos + 1));
            cout << line << "\n";
            break;
        }
        output << line << "\n";
        // cout << front << "\n";
        // cout << back << "\n";
        // cout << line << "\n";
    }
    sstr << back;
    long npoint;
    sstr >> npoint;
    sstr >> npoint;
    output << front << "= " << npoint << "\n";
    cout << "npoint = " << npoint << "\n";
    double x, y, z;
    long n1, n2;
    string tmp;
    output << scientific << setprecision(16);
    for (long i = 0; i < npoint; ++i)
    {
        getline(input, line);
        tmp = strip(line);
        if (tmp == "")
        {
            --i;
            continue;
        }
        // 重复使用这个的话记着使用 clear 不使用的话会发生错误
        // 原理不详
        // sstr.clear();
        // sstr << tmp;
        // sstr >> x >> y >> z >> n1 >> n2;
        // output << x << "    " << y << "    "
        //        << z << "    " << n1 << "\n";

        // 直接取字符串
        pos = tmp.find_last_of("\t ");
        tmp = tmp.substr(0, pos);
        output << tmp << "\n";
    }

    while (getline(input, line))
        output << line << "\n";
    return 0;
}
